<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="工厂">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            filterable
          >
            <el-option
              v-for="item in plantListLable"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="存货编码">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入存货编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="图号">
          <el-input
            v-model="searchParam.figureNumber"
            placeholder="请输入图号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select
            v-model="searchParam.materialType"
            placeholder="请选择物料类型"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('MaterialType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="stopParam()"
          >批量停用</el-button
        >
        <el-button type="primary" @click="materialImport">
          <template #icon><i-ep-upload /></template>导入
        </el-button>
        <el-button
          type="primary"
          class="ml-3"
          @click="
            useDownload(
              '/mdm/mdmmaterial/export',
              '物料主数据',
              searchParam,
              true,
              '.xls'
            )
          "
        >
          <template #icon><i-ep-download /></template>导出
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="table1"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="物料编号"
          prop="materialCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column label="物料类型" prop="materialType" min-width="100">
          <template #default="scope">
            {{ useDictionary("MaterialType", scope.row.materialType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="物料分类"
          prop="materialClassification"
          min-width="100"
        >
          <template #default="scope">
            {{
              useDictionary(
                "MaterialClassify",
                scope.row.materialClassification
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="物料组"
          prop="materialGroupName"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="工厂编号"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="图号"
          prop="figureNumber"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="短号"
          prop="shortCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="外来编号"
          prop="srcCode"
          min-width="100"
          show-overflow-tooltip
        />
        <!--<el-table-column
          label="物料状态"
          prop="materialState"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MaterialState", scope.row.materialState) }}
          </template>
        </el-table-column>-->
        <el-table-column
          label="计量单位"
          prop="unit"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="HT/QT"
          prop="htqt"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="P/M"
          prop="pm"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="M/炉"
          prop="mfurnace"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="M/包"
          prop="mpackage"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="包/炉"
          prop="bagStove"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="单重（KG)"
          prop="singleWeight"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="模重（KG)"
          prop="modelWeight"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="重量Kg/炉"
          prop="kgStove"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="出品率%"
          prop="yield"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="浇注节拍 （秒/模)"
          prop="pouringCycleTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="熔炼理论时长(分)"
          prop="smeltDurationTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="浇注理论时长（分）"
          prop="theoreticalDurationTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="包待时长（分）"
          prop="packageWaitingTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="炉待（分）"
          prop="furnaceWaitingTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="生产周期(天)"
          prop="productionCycle"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="挂抛数量(件/挂)"
          prop="quantityPerHanger"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="是否可炉头"
          prop="isHead"
          min-width="110"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("YesNo", scope.row.isHead) }}
          </template>
        </el-table-column>
        <el-table-column
          label="是否可炉尾"
          prop="isTail"
          min-width="110"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("YesNo", scope.row.isTail) }}
          </template>
        </el-table-column>
        <el-table-column
          label="计量单位"
          prop="unit"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="挂抛(次数)"
          prop="hangingThrowingNum"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="滚抛(件/次)"
          prop="rollThrowingNum"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="终检效率(件/小时)"
          prop="inspectEfficiency"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="终检节拍(件/小时)"
          prop="inspectBeat"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />

        <el-table-column
          label="X光效率(秒/次)"
          prop="xefficiency"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="X光检验频率(M/炉)"
          prop="xfrequency"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="磁粉检验频率(M/炉)"
          prop="powderFrequency"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="自动研磨设备编号"
          prop="automaticGrindCode"
          min-width="200"
          show-overflow-tooltip
          header-align="center"
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
                ><i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="配置"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                :disabled="scope.row.materialType != '3'"
                @click="configDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="handleTableDelete(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mdmmaterial-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <mdmmaterial-config
      :visible="configureDialog.visible"
      :title="configureDialog.title"
      :data="configureDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="configureDialog.readvisible"
      @change-visible="configVisible"
    />
    <!-- 导入 -->
    <ImportExcel ref="materialImportRef" />
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table
      ref="uploadErrorRef"
      :errorDataList="errorDataList"
      :promptDataList="promptDataList"
      :paramList="paramList"
      :listWorkOrder="listWorkOrder"
      @changelist="changelist"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMMATERIAL",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mdm/mdmmaterial/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialCode: "",
  materialName: "",
  materialType: "",
  plantId: "",
  figureNumber: "",
};

const deleteParam = {
  api: "/mdm/mdmmaterial/delete",
  data: {},
};
// 批量停用接口
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mdm/mdmmaterial/disabled",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};

// 数据请求错误后处理
function requestError() {}

const table1 = ref([]);
const mdmmatgroup: any = ref([]);
const plantListLable: any = ref([]);
const dataCallBack = ref(async (res: any) => {
  const resMdmmatgroup = await request({
    url: "mdm/mdmmatgroup/getList",
    method: "post",
    data: {},
  });
  mdmmatgroup.value = resMdmmatgroup.data;

  const plantList = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });

  plantListLable.value = plantList.data;
  if (searchParam.value.plantId == null) {
    searchParam.value.plantId = plantListLable.value[0].id;
  }

  for (let j = 0; j < res.length; j++) {
    for (let i = 0; i < mdmmatgroup.value.length; i++) {
      if (res[j].materialGroupId == mdmmatgroup.value[i].id) {
        res[j].materialGroupId = mdmmatgroup.value[i].materialGroupName;
      }
    }
  }
  // for (let j = 0; j < res.length; j++) {
  //   for (let i = 0; i < plantListLable.value.length; i++) {
  //     if (res[j].plantCode == plantListLable.value[i].organizationCode) {
  //       res[j].plantCode = plantListLable.value[i].organizationName;
  //     }
  //   }
  // }
  table1.value = res;

  return table1.value;
}); // 无需二次数据处理&不传赞数也行

// const dataCallBack = ref(undefined);
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const configureDialog: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getConfig(id: string) {
  request({
    url: `/mdm/mdmmaterial/get/${id}`,
    method: "get",
  }).then((data) => {
    configureDialog.data = data.data;

    configureDialog.visible = true;
  });
}

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mdm/mdmmaterial/get/${id}`,
    method: "get",
  }).then((data) => {
    addDialog.data = data.data;
    addDialog.data.yields = data.data.yield;

    addDialog.visible = true;
  });
}

/** 打开物料主数据表单弹窗 */
function configDialog(roleObj?: Object) {
  if (roleObj) {
    configureDialog.title = "产品成份配置";
    getConfig(roleObj.id);
  } else {
    configureDialog.title = "产品成份配置";
    configureDialog.visible = true;
  }
  configureDialog.readvisible = false;
}

/** 打开物料配置表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改物料主数据";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增物料主数据";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开物料主数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "物料主数据详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
  addDialog.rulesValue = false;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function configVisible(value: boolean) {
  configureDialog.visible = value;
  if (!value) {
    configureDialog.data = {};
  }
}
// 点击同步按钮
const syncBtn = () => {
  ElMessageBox.confirm("确定同步吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mdm/mdmmaterial/synchronization",
        method: "post",
        data: {},
      });

      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "同步成功",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消同步",
      });
    });
};

// 导入周数据
const materialImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
const promptDataList = ref([]);
const listWorkOrder = ref([]);
const paramList = ref({});
async function materialImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mdm/mdmmaterial/upload", formdata, config)
    .then((res: any) => {});
}
const changelist = () => {
  search();
};
const materialImport = () => {
  let newSearchParam = { ...searchParam.value };
  let params = {
    title: "导入物料主数据",
    tempApi: "/mdm/mdmmaterial/exportTemp", //模板下载
    importApi: materialImportApiFunc, // 导入
    getTableList, // 成功后回调
    isShowTemp: true, // 是否显示下载模板
    fileTypes: ".xls",
    searchParam: newSearchParam,
  };
  materialImportRef.value.acceptParams(params);
};
</script>
<style lang="scss" scoped>
/* 去除选中时蓝色边框（下面两个都要加上） */

// :deep(.el-input .el-input__wrapper.is-focus) {
//   outline: none !important;
// }
// :deep(.el-select .el-input.is-focus .el-input__wrapper) {
//   outline: none !important;
// }

// :deep(.el-select .el-input .el-input__inner) {
//   border-color: #dcdfe6 !important;
//   outline: none;
// }
</style>
